package org.spring.springboot.app.user.sysuser.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spring.springboot.app.base.Menu;
import org.spring.springboot.app.base.R;
import org.spring.springboot.app.base.Type;
import org.spring.springboot.app.sys.role.domain.vo.SysRoleAddUserVO;
import org.spring.springboot.app.user.sysuser.dao.SysUserDao;
import org.spring.springboot.app.user.sysuser.domain.bo.SysUserBO;
import org.spring.springboot.app.user.sysuser.domain.po.SysUserPO;
import org.spring.springboot.app.user.sysuser.domain.po.SysUserRolePO;
import org.spring.springboot.app.user.sysuser.domain.vo.*;
import org.spring.springboot.app.user.sysuser.service.ISysUserService;
import org.spring.springboot.util.RedisUtils;
import org.spring.springboot.util.IdGen;
import org.spring.springboot.util.IpUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class SysUserServiceImpl implements ISysUserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserDao sysUserDao;

    // key生成器,redis生成key必须用
    @Autowired
    private RedisUtils redisUtils;

    // 序列化对象redis处理方法
    @Autowired
    private RedisTemplate redisTemplate;
    // String储存redis处理方法,使用方法同上
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public SysUserPO find(String id) {

        return sysUserDao.selectByPrimaryKey(id);

    }

    @Override
    public List<SysUserPO> findAll(UserSearchVo vo) {
        return sysUserDao.selectAll(vo,vo.getPageNum(), vo.getPageSize());
    }


    @Override
    public int update(SysUserAddVO vo) {
        SysUserPO po = new SysUserPO();
        SysUserRolePO p = new SysUserRolePO();
        if(sysUserDao.getCountLoginName(po) > 0){
            return 105;
        }
        BeanUtils.copyProperties(vo, po);
        po.preUpdate();
        if (vo.getRoles() != null && vo.getRoles().size() > 0) {
            sysUserDao.deleteUserRoleByUserId(po.getId());
            for (SysRoleAddUserVO role : vo.getRoles()) {
                p.setUserId(po.getId());
                p.setRoleId(role.getId());
                sysUserDao.insertUserRole(p);
            }
        }
        return sysUserDao.updateByPrimaryKeySelective(po);
    }

    @Override
    public int delete(String id) {
        SysUserPO sysUserPO = new SysUserPO();
        sysUserPO.setId(id);
        sysUserPO.preDelete();
        return sysUserDao.updateByPrimaryKeySelective(sysUserPO);
    }

    @Override
    public int deletes(String ids) {
        SysUserPO sysUserPO = new SysUserPO();
        String[] id_s = ids.split(",");
        sysUserPO.preDelete();
        int count = 0;
        for (String id : id_s) {
            sysUserPO.setId(id);
            count += sysUserDao.updateByPrimaryKeySelective(sysUserPO);
        }
        return count;
    }

    @Override
    public SysUserBO findByLoginId(String loginId) {
        return sysUserDao.findByLoginId(loginId);
    }

    @Override
    public R<UserLoginResVO> login(UserLoginReqVO userLoginReqVO, HttpServletRequest request) {
        R result = new R();
        SysUserBO user = sysUserDao.findByLoginId(userLoginReqVO.getLoginId());
        if (user == null) {
            result.setType(Type.NotFoundError);
            return result;
        }
        if ("1".equals(user.getDelFlag())) {
            result.setType(Type.DataDelError);
            result.setMessage("账号已被禁用");
            return result;
        }
        if (!"1".equals(user.getLoginFlag())) {
            result.setType(Type.DataDelError);
            result.setMessage("账号已被禁用");
            return result;
        }
        if (!user.getPassword().equalsIgnoreCase(userLoginReqVO.getPassword())) {
            result.setType(Type.PowerValidateFail);
            result.setMessage("密码错误");
            return result;
        }
        //修改登录时间和ip
        user.setLoginDate(new Date(System.currentTimeMillis()));
        user.setLoginIp(IpUtil.getIpAddr(request));
        user.preUpdate();
        sysUserDao.updateByPrimaryKeySelective(user);
        UserLoginResVO res = new UserLoginResVO();
        BeanUtils.copyProperties(user, res);
        result.setData(res);
        return result;
    }

    @Override
    public R<UserRegistReqVO> regist(UserRegistReqVO userRegistReqVO, HttpServletRequest request) {
        R result = new R();
        SysUserPO user = sysUserDao.findByLoginId(userRegistReqVO.getLoginId());
        //检查用户是否注册
        if (user != null) {
            result.setType(Type.ExistError);
            return result;
        }
        user = new SysUserPO();
        //user.setId(IdGen.uuid());
        user.setCompanyId("1");
        user.setOfficeId("1");
        user.setLoginName(IdGen.uuid());
        user.setPassword(userRegistReqVO.getPassword());
        user.setName(userRegistReqVO.getLoginId());
        user.setPhone(userRegistReqVO.getLoginId());
        user.setMobile(userRegistReqVO.getLoginId());
        user.setUserType("1");
        // user.setCreateBy("1");
        //  user.setCreateDate(new Date(System.currentTimeMillis()));
        // user.setUpdateBy("1");
        // user.setUpdateDate(new Date(System.currentTimeMillis()));
        user.setLoginFlag("1");
        //  user.setDelFlag("0");
        user.preInsert();
        int code = sysUserDao.insertSelective(user);
        if (code == 0) {
            result.setType(Type.OperError);
            result.setMessage("保存失败");
        }
        return result;
    }

    @Override
    public List<UserRoleQueryVO> queryUserRoles(String id) {
        return sysUserDao.queryUserRoles(id);
    }

    @Override
    public int resetPassword(String id){
        SysUserPO po = new SysUserPO();
        po.setPassword("670b14728ad9902aecba32e22fa4f6bd");
        po.setId(id);
        po.preUpdate();
        return sysUserDao.updateByPrimaryKeySelective(po);
    }

    @Override
    public int setPassword(String id,String password){
        SysUserPO po = new SysUserPO();
        po.setPassword(password);
        po.setId(id);
        po.preUpdate();
        return sysUserDao.updateByPrimaryKeySelective(po);
    }

    @Override
    public List<Menu> selectUserMenus(String id) {
        return sysUserDao.selectUserMenus(id);
    }
    @Override
    public int getUserTargetCount(UserCheckVo vo) {
        return sysUserDao.getUserTargetCount(vo);
    }

    @Override
    public R insertUserInfo(SysUserAddVO vo) {
        R r = new R();
        SysUserPO po = new SysUserPO();
        BeanUtils.copyProperties(vo, po);
        if(sysUserDao.getCountLoginName(po) > 0){
            return r.fail().setType(Type.ParamValidateFail);
        }
        po.preInsert();
        if (vo.getRoles()!=null  &&  vo.getRoles().size() > 0) {
            for (SysRoleAddUserVO role : vo.getRoles()) {
                SysUserRolePO p = new SysUserRolePO();
                p.setUserId(po.getId());
                p.setRoleId(role.getId());
                sysUserDao.insertUserRole(p);
            }
        }
        if(sysUserDao.insertSelective(po)<1){
            return r.fail().setMessage("保存失败");
        }
        SysUserAddResVO resVO = new SysUserAddResVO();
        resVO.setId(po.getId());
        resVO.setName(po.getName());
        return r.success().setData(resVO);
    }
}
